<template>
  <div class="add-or-edit-product factory-container">
    <header class="mb20 pd20 header-wrap">
      <div>
        <template v-if="stepsActive === 1 || stepsActive === 2">
          <div>
            <!-- v-show="actionType === 're-applay'" -->
            <el-button type="primary" v-show="actionType === 're-applay'" plain @click="processPass">通过审核</el-button>
            <el-button type="primary" v-show="actionType === 're-applay'" plain @click="overruleVisible = true">驳回</el-button>
            <el-button v-if="actionType === 're-applay'" type="primary" @click="toEditPath">编辑商品</el-button>
            <template v-else>
              <el-button type="primary" plain :icon="Search" @click="clickSave('review')">保存并预览商品</el-button>
              <el-button type="primary" @click="clickSave(false)">发布商品</el-button>
            </template>
            <!-- <el-button type="primary" @click="back">返回</el-button> -->
          </div>
        </template>
      </div>
      <!-- <el-button @click="toPath">返回上一页</el-button> -->
      <el-button @click="back">返回上一页</el-button>
    </header>
    <!-- <div class="line"></div> -->

    <!-- 步骤条 -->
    <el-steps class="mt66" style="max-width: 100%" :active="stepsActive" finish-status="success">
      <el-step title="选择发布类目" @click="changeSteps(0)"> </el-step>
      <el-step title="编辑商品信息" @click="changeSteps(1)" />
      <el-step title="提交商品发布" @click="changeSteps(2)" />
    </el-steps>

    <div class="steps1" v-show="stepsActive === 0">
      <!-- 第一步 -->
      <p class="f18 mb24">选择商品类目</p>
      <el-form
        :disabled="actionType === 're-applay'"
        :model="form"
        ref="formRef"
        label-width="auto"
        :rules="rules"
        style="width: 100%"
      >
        <el-form-item label="商品分类" prop="categoryId">
          <el-tree-select
            :disabled="JSON.stringify(_optionInfo) !== '{}'"
            ref="treeSelectRef"
            v-model="form.categoryId"
            node-key="categoryId"
            default-expand-all
            :data="products"
            :check-strictly="false"
            :render-after-expand="false"
            :props="{
              label: 'name',
              value: 'categoryId'
            }"
            style="width: 100%"
          />
          <!-- @node-click="handleNodeClick" -->
        </el-form-item>
        <el-form-item label="">
          <el-checkbox v-model="form.agree" size="large">
            我已阅读如下规则<el-button link type="primary" @click="dialogVisibleAgree = true">xxx平台规则</el-button>
          </el-checkbox>
        </el-form-item>
      </el-form>
      <div class="btn-wrap">
        <el-button type="default" @click="toPath">返回</el-button>
        <el-button type="primary" @click="nextStep(1)">下一步</el-button>
      </div>
    </div>
    <div class="steps2" v-show="stepsActive === 1">
      <baseinfo ref="baseinfoRef" :optionInfo="optionInfo" :Enums="Enums" :categoryId="form.categoryId"></baseinfo>
      <div class="block mb40"></div>
      <attr ref="attrRef" :optionInfo="optionInfo" :Enums="Enums" :categoryId="form.categoryId"></attr>
      <div class="block mb40"></div>
      <sku ref="skuRef" :optionInfo="optionInfo" :Enums="Enums" :categoryId="form.categoryId"></sku>
      <div class="block mb40"></div>
      <editor :optionInfo="optionInfo" ref="editorRef"></editor>
      <!-- <div class="btn-wrap mt20">
        <el-button type="primary" @click="nextStep(2)">下一步</el-button>
      </div> -->
    </div>
    <div class="steps3" v-show="stepsActive === 2">
      <div class="mt44" style="text-align: center">
        <el-button v-if="actionType === 're-applay'" type="primary" @click="toEditPath">编辑商品</el-button>
        <el-button v-else type="primary" @click="reportPoducts">发布商品</el-button>
      </div>
    </div>

    <!-- 平台规则 -->
    <el-dialog v-model="dialogVisibleAgree" title="平台规则" width="60%">
      <div v-html="agreementHtml"></div>
    </el-dialog>

    <!-- 驳回弹窗 -->
    <el-dialog v-model="overruleVisible" modal-class="log-dialog" width="900" title="商品审核驳回" align-center center>
      <div class="goods-detail">
        <img :src="editDetailInfo.mainPicUrl || defaultImage" alt="" />
        <div>
          <div class="goods-name">{{ editDetailInfo.productName }}</div>
          <div class="goods-info">
            <div>上架类目：{{ getClassify(editDetailInfo.categoryId) }}</div>
            <div>型号：{{ editDetailInfo.modeCode }}</div>
            <!-- <div>分类：{{ editDetailInfo.modeCode }}</div> -->
            <div>
              ID：{{ editDetailInfo.productId }}
              <div class="area">
                运营区域：
                <template v-if="editDetailInfo.buinessAddress.length > 0">
                  <el-tag type="primary" v-for="item in editDetailInfo.buinessAddress" :key="item.id">{{
                    item.buinessAddress
                  }}</el-tag>
                </template>
                <span v-else>--未设置--</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="blank"></div>
      <el-form-item label="备注" class="remark">
        <el-input
          v-model="tips"
          class="areaText"
          :rows="10"
          type="textarea"
          :placeholder="`驳回信息应该具体、清晰、准确，明确说明驳回的原因和解决方案。例如：商品标题不清晰、描述信息不真实、图片质量低下等；违反相关法律法规和平台规则，如侵犯知识产权、虚假广告等；商品信息不完整、缺少关键信息，如价格、规格、包含内容等；商品违反相关环保法规，如使用禁用物质等。驳回信息还可以提供相关参考资料或链接，以帮助卖家了解相关规定和要求。`"
        />
        <div style="color: red">温馨提示：请详细描述驳回原因，以便商家明确知晓并更改商品信息 ~ ~</div>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="overruleVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOverrule"> 确认驳回 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 工厂/商家未设置返佣阻断审核 -->
    <el-dialog v-model="renewalDialog" width="474" align-center center @close="renewalDialog = false">
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">
        该供应商未设置返佣规则，或未设置对应等级的商家返佣，不允许发布商品
      </div>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="renewalDialog = false">取消</el-button>
          <el-button class="btn" type="primary" @click="renewalDialog = false"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Delete, Edit, Search, Share, Upload, Tickets } from "@element-plus/icons-vue";
import baseinfo from "./components/baseinfo.vue";
import attr from "./components/attr.vue";
import sku from "./components/sku.vue";
import editor from "./components/editor.vue";
import {
  getcategoryList,
  getAgreementList,
  getEnumAll,
  saveProduct,
  getProductDetail,
  eidtProduct
} from "@/api/products/specifications";
import { audit } from "@/api/products/manage";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import defaultImage from "@/assets/images/products/default.png";
import { findAncestorsById } from "@/utils";

const stepsActive = ref(0);
const form = ref({ categoryId: "", agree: true });
const formRef = ref();
const rules = ref({
  categoryId: [{ required: true, message: "请选择商品分类", trigger: ["blur", "change"] }]
});
const products = ref([]);
const agreementHtml = ref(""); //协议内容
const dialogVisibleAgree = ref(false);
const Enums = ref([]);
const baseinfoRef = ref();
const attrRef = ref();
const skuRef = ref();
const editorRef = ref();
const actionType = ref("add");
const productId = ref("");
const redirect = ref("");
const editDetailInfo = ref({}); //编辑时，当前的商品详情
const optionInfo = ref({
  actionType: "add",
  editDetailInfo: {}
});
const overruleVisible = ref(false); //驳回弹窗
const tips = ref(""); //驳回内容

onMounted(async () => {
  productId.value = route.query.productId;
  redirect.value = route.query.redirect;
  if (productId.value) {
    console.log("route====", route);
    if (route.name.includes("edit")) {
      actionType.value = "edit";
      stepsActive.value = 1;
    } else if (route.name.includes("copy")) {
      actionType.value = "copy";
      stepsActive.value = 1;
    } else if (route.name.includes("re-applay")) {
      actionType.value = "re-applay";
      stepsActive.value = 1;
    }
  }
  console.log("操作类型===", actionType.value, "productId===", productId.value);

  getProducts();
  getAgreement();

  const _Enums = await getEnumAll(); //查询完整的数据字典
  Enums.value = _Enums.data;

  if (actionType.value !== "add") {
    getProductDetail({ productId: productId.value }).then(res => {
      if (res.code === 200) {
        console.log("商品详情===", res.data);
        form.value.categoryId = res.data.categoryId;
        editDetailInfo.value = res.data;
        optionInfo.value = {
          actionType: actionType.value,
          editDetailInfo: editDetailInfo.value
        };
      }
    });
  }
});

const clickSave = async (review = false) => {
  // type 1-预发布 2-保存并发布
  //下一步，进行校验
  const flag = await nextStep(2, false);
  flag && reportPoducts(review);
};

const back = () => {
  if (redirect.value) {
    const query = route.query;
    delete query.redirect;
    router.push({ path: redirect.value, query: query });
  }
};

const getClassify = val => {
  const parentArr = findAncestorsById(val, products.value, "categoryId");
  const nameArr = parentArr.map(item => item.name);
  return nameArr.join(">");
};

// 审核通过
const processPass = () => {
  audit({ productIds: [editDetailInfo.value.productId], auditingStatus: 1 }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "审核已通过",
        type: "success"
      });
      back();
    }
  });
};

const confirmOverrule = () => {
  // 确认驳回
  audit({ productIds: [editDetailInfo.value.productId], auditingStatus: 2, newOverruleReason: tips.value }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "已驳回",
        type: "success"
      });
      back();
    }
  });
};

//跳转到编辑页面
const toEditPath = () => {
  router.push({
    path: "/products/manage/edit",
    query: { productId: editDetailInfo.value.productId, redirect: "/products/manage", tabs: route.query.tabs || "2" }
  });
};

const getAgreement = () => {
  getAgreementList().then(res => {
    if (res.code === 200) {
      console.log("协议内容===", res);
      agreementHtml.value = res.data[0].content;
    }
  });
};

//获取商品分类tree
const getProducts = () => {
  getcategoryList({ searchkey: "" }).then(res => {
    if (res.code === 200) {
      // console.log("这是商品分类====", res.data);
      products.value = res.data;
    }
  });
};

const changeSteps = val => {
  nextStep(val);
};
const preStep = () => {
  if (stepsActive.value-- < 0) stepsActive.value = 0;
};

const Params = ref({});
const nextStep = async (num, isNext = true) => {
  if (num === 1) {
    formRef.value.validate((valid, fields) => {
      if (valid) {
        console.log("第一步的form===", form.value);
        if (form.value.agree) {
          if (isNext) stepsActive.value = num;
        } else {
          ElMessage({
            message: "请同意平台规则！",
            type: "error"
          });
        }
      }
    });
  } else if (num === 2) {
    let flag = false;
    await Promise.all([
      baseinfoRef.value.getBaseInfo(),
      attrRef.value.getAttrForm(),
      skuRef.value.getSkuList(),
      editorRef.value.getEditor()
    ]).then(res => {
      const params = {
        publishStatus: 2,
        ...res[0],
        ...res[1],
        specificationList: res[2].specesList,
        skuList: res[2].skuList,
        shopDetail: res[3].valueHtml
      };
      Params.value = params;
      console.log("发布商品数据===", params);
      if (isNext) stepsActive.value = num;
      flag = true;
    });
    return flag;
  } else {
    if (isNext) stepsActive.value = num;
  }
};

// 路由跳转
import { ElMessage } from "element-plus";
const toPath = () => {
  router.push({
    path: "/products/manage"
  });
};

const reportPoducts = review => {
  console.log("操作类型===", actionType.value);
  if (actionType.value === "add") {
    saveProduct(Params.value).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "发布成功！",
          type: "success"
        });
        if (review) {
          //本页签内跳转成详情页
          router.push({
            path: "/products/manage/edit",
            query: {
              productId: res.data,
              redirect: "/products/manage",
              showBack: true
            }
          });

          // 预览
          toPreview({ path: "/products/manage/preview", query: { id: res.data } });
          // toPreview({ path: "/products/manage/preview", query: { id: "1818122010435973122" } });
        } else {
          back();
        }
      }
    });
  } else if (actionType.value === "edit") {
    editorRef.value.saveRichTextFun();
    const _Params = JSON.parse(JSON.stringify(Params.value));
    delete _Params.shopDetail;
    console.log("编辑的参数===", _Params);
    eidtProduct({ ...editDetailInfo.value, ..._Params, productId: productId.value }).then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "商品编辑成功",
          type: "success"
        });
        if (review) {
          //如果存在临时id，说明需要走审核流程，不能继续待在编辑页了，必须强制返回列表页
          if (res.data?.tempLinkId) {
            router.push({
              path: "/products/manage"
            });
          }

          // 预览
          toPreview({ path: "/products/manage/preview", query: { id: res.data?.tempLinkId || res.data?.productId } });
          // toPreview({ path: "/products/manage/preview", query: { id: "1818122010435973122" } });
        } else {
          back();
        }
      }
    });
  } else if (actionType.value === "copy") {
    // 做的是按钮级别的操作，不再需要走详情页面之后再确认copy
  } else if (actionType.value === "re-applay") {
    // 做的是按钮级别的操作，不再需要走详情页面之后再确认applay
  }
};

const toPreview = async pathObj => {
  const routeUrl = router.resolve(pathObj);
  window.open(routeUrl.href, "_blank");
};

const renewalDialog = ref(false);
</script>

<style lang="scss" scoped>
.header-wrap {
  position: sticky;
  top: 0px;
  background-color: white;
  z-index: 99;
  margin: 0 -20px;
  border-bottom: 1px solid #e1effe;
}
:deep(.el-step__title) {
  cursor: pointer;
}
:deep(.el-dialog__header) {
  padding: 20px;
}
:deep(.el-dialog--center .el-dialog__body) {
  padding: 25px 25px 30px 25px;
}
.btn-wrap {
  text-align: center;
}
.block {
  height: 20px;
  background-color: #f5f7fa;
  margin: 0 -20px;
}
:deep(.el-dialog__header) {
  text-align: left;
}
.log-dialog {
  .goods-detail {
    display: flex;
    gap: 20px;
    line-height: 2;
    padding: 0 20px;

    img {
      width: 150px;
      height: 150px;
      border-radius: 4px;
    }

    > div {
      width: 100%;
    }

    .goods-name {
      font-size: 18px;
      color: #007dff;
    }

    .goods-info {
      text-align: left;
      position: relative;
      width: 100%;

      .area {
        color: #007dff;
        cursor: pointer;
        position: absolute;
        bottom: 0;
        right: 0;

        .el-tag {
          margin-left: 8px;
        }
      }
    }
  }
  .blank {
    height: 10px;
    background: #eef1f4;
    margin: 20px -25px;
  }
  .remark {
    font-size: 14px;
    display: flex;

    .label {
      color: #86909c;
      white-space: nowrap;
    }
    :deep(.el-textarea__inner) {
      background-color: #f2f3f5;
      box-shadow: none;
      padding: 20px;
    }
  }
}
.add-or-edit-product {
  padding: 20px;
  padding-top: 0 !important;
  height: calc(100vh - 90px);
  overflow-y: auto;
  :deep(.el-steps) {
    padding-left: 16%;
    .el-step__icon-inner {
      font-weight: normal;
    }
    .el-step {
      position: relative;
      flex-basis: 40% !important;
      .el-step__head.is-success {
        border-color: transparent;
        .el-step__line {
          height: 0;
          background-color: transparent;
        }
        .el-step__icon.is-text {
          background-color: #e8f3ff;
          color: #165dff;
        }
      }
      .el-step__head.is-process {
        .el-step__icon.is-text {
          border: none;
          background-color: #165dff;
          color: white;
          .el-step__icon-inner {
            font-weight: normal;
          }
        }
      }
      .el-step__head.is-wait {
        .el-step__icon.is-text {
          border: none;
          background-color: #f2f3f5;
          color: #4e5969;
        }
      }
      .el-step__title.is-wait {
        color: #4e5969;
      }
      .el-step__main {
        position: absolute;
        top: -8px;
        left: 40px;
        .el-step__title {
          font-weight: normal;
          &.is-success {
            color: #4e5969;
          }
        }
      }
      .el-step__line-inner {
        border: none;
      }
      .el-step__line {
        left: 160px;
        right: 25px;
        height: 0px;
        background-color: transparent;
        border-bottom: 1px dashed #d8d8d8;
      }
    }
  }
  header {
    display: flex;
    justify-content: space-between;
  }
  .line {
    height: 1px;
    background-color: #e1effe;
    margin: 0 -20px;
  }
}
</style>
